package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;

import com.tanhua.dubbo.db.api.FreezeApi;
import com.tanhua.dubbo.db.api.UserApi;
import com.tanhua.dubbo.db.api.UserInfoApi;

import com.tanhua.model.db.Freeze;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FreezeApi freezeApi;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private HuanXinTemplate template;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public User findByMobile(String mobile) {
        User user = userApi.findByMobile(mobile);
        return user;
    }

    //登录-验证码校验

    public Map loginVerification(String phone, String verificationCode) {

        //1.从redis中获得验证码
        String code = redisTemplate.opsForValue().get("_code" + phone);

        //2.对验证码进行校验（验证码是否存在，是否和输入的验证码一致

        if (code.isEmpty() || !code.equals(verificationCode)) {
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());

        }

        //3.删除验证码
        redisTemplate.delete("_code" + phone);

        //4.判断手机号是否存在
        User user = userApi.findByMobile(phone);
        boolean isNew = false;


        //5、如果用户不存在，创建用户保存到数据库中
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");
            Long id = userApi.save(user);
            user.setId(id);
            user.setHxUser(Constants.HX_USER_PREFIX + id);
            user.setHxPassword(Constants.INIT_PASSWORD);
            isNew = true;
            userApi.update(user);
            template.createUser(Constants.HX_USER_PREFIX + id, Constants.INIT_PASSWORD);


        }

        try {
            //注册或者登录后发送信息给rabbitMQ,
            Map<String, String> map = new HashMap<>();
            map.put("userId", user.getId().toString());
            map.put("type", isNew?"0102":"0101"); //0102表示注册.0101表示登录
            map.put("logTime", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            map.put("busId", null);//业务id 登录注册不需要

            String msg = JSON.toJSONString(map);
            rabbitTemplate.convertAndSend("tanhua.log.exchange", "log.user", msg);//交换机,路由键,信息
        } catch (AmqpException e) {
            e.printStackTrace();
        }


        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);

        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map resMap = new HashMap();
        resMap.put("token", token);
        resMap.put("isNew", isNew);

        //查询该用户否被冻结
        Long userId = user.getId();
        String key = Constants.USER_FREEZE+userId;

        Freeze freeze = freezeApi.findFreezeByUserId(userId);
        if (freeze == null){
            //如果冻结列表为空直接返回
            return resMap;
        }
        UserInfo userInfo = userInfoApi.findById(userId);
        //获取从redis中获取的数据
        String freezeTime =redisTemplate.opsForValue().get(key);
        Integer freezingTime = freeze.getFreezingTime();
        if (freezeTime == null && freezingTime != 3){
            userInfo.setUserStatus("1");
            userInfoApi.updateUserInfo(userInfo);
            return resMap;
        }
        if (freezeTime != null ){
            if (userInfo.getUserStatus().equals("2") && freeze.getFreezingRange()==1){
                throw new BusinessException(ErrorResult.freezeError());
            }
        }
        return resMap;
    }

    public void saveUserInfo(UserInfo userInfo) {

        userInfoApi.save(userInfo);

    }

    public void updateUserInfo(Long userId, MultipartFile headPhoto) throws IOException {
        //上传到阿里云, 湖区url访问路径
        String upload = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        boolean detect = aipFaceTemplate.detect(upload);
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }

        //更新


        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setAvatar(upload);

        userInfoApi.updateUserInfo(userInfo);


    }
}
